package sto.orz.json.webapp.action;

import java.util.HashMap;
import java.util.Map;

import ognl.Ognl;
import ognl.OgnlException;
import sto.orz.json.JSONResponse;

/*******************************************************************************
 * request >>>
 * 
 * [GET] model="object"
 *       model : 可选,为目标Model的别名/类名(取决于ClassLoader)
 * 
 * [POST] LOTEX_JSON_ARGS = [
 *            "name" : "datasource",
 *            "value" : {
 *                "id":"12"
 *            },
 *            ["name"]
 *        ]
 * LOTEX_JSON_ARGS (@see BaseJsonAction) :
 *     String modelName;
 *     Map modelValue(以此在数据库中查找该model)；
 *     Array select(返回列列名数组)。
 *          
 * 备注：目前为简化配置，必须指定id，且数据表 必须有id列。
 * 
 * response <<<
 * [JSON] {
 *     done : true/false,
 *     result: {name:"test"},
 *     [message: ""]
 * }
 * 说明 :
 *     done: 可选，动作执行成功为true，反之为false;
 *     result: 以JSONObject(Map格式)返回数据，
 *     message：可选，返回服务器消息，例如错误消息。
 ******************************************************************************/
public class GetModelAction extends BaseJSONAction {
	private static final long	serialVersionUID	= 2186644367305518312L;

	public String todo(String modelName, HashMap<String, String> model,
			Object[] selects) {
		Class<?> modelClass;
		try {
			modelClass = loadModel(modelName);
		} catch (Exception e1) {
			return message("Request domain model not found!");
		}

		Object modelId = model.get("id");
		if (modelId == null)
			return message("Must set model id now!");

		// read model from database by id
		Object object = dao.findUniqueBy(modelClass, "id", modelId);
		if (object == null)
			return message("Model not exist!");

		Map<String,Object> result = new HashMap<String,Object>();
		for (int i = 0; i < selects.length; i++) {
			String property = (String) selects[i];
			try {
				result.put(property, Ognl.getValue(property, object));
			} catch (OgnlException e) {
				return message("Model property [" + property + "] not exist!");
			}
		}

		json = new JSONResponse(result);

		return JSON_RESPONSE;
	}
}
